package com.example.smartphonecontext;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;


import android.R.bool;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SensorValue extends Activity implements OnClickListener {

	//TODO: 실행 시간, 10초는 20
	final static public int SENSOR_TERM = 20;
	
	
	
	final static public boolean FILE_OUT = false;

	private SensorManager sm;
	private SensorEventListener accl, lightl, gryl, magl;
	private Sensor accSensor, lightSensor, grySensor, magSensor;

	private LocationManager lm;
	private LocationListener lgl, lnl;
	// private Location location_Gps, location_Network;

	private AudioReader audioReader;
	private int sampleRate = 8000;
	private int inputBlockSize = 256;
	private int sampleDecimate = 1;

	public static AudioManager ap;
	TextView ax, ay, az, light, gx, gy, gz, mx, my, mz, db, speedview, la_gps,
			lo_gps, la_ap, lo_ap, s_gps, s_ap;
	Button fileout;
	EditText edit;
	ActivityManager am;
	
	Button sensorSwBtn;
	// EditText time;

	Handler handler;
	
	private double lat = 0;
	private double lng = 0;
	private double prelat = 0;
	private double prelng = 0;

	private long curTime;
	private long preTime;
	private double deltaTime;
	private float[] distance = new float[2];
	private int speed_ap, speed_gps;
	private int resultspeed;

	private float[] decibel = new float[100];
	private float[] light_array = new float[100];
	private float[] ax_array = new float[100];
	private float[] ay_array = new float[100];
	private float[] az_array = new float[100];
	private float[] gx_array = new float[100];
	private float[] gy_array = new float[100];
	private float[] gz_array = new float[100];

	private float axvar, ayvar, azvar, gxvar, gyvar, gzvar, dbavr, dbvar,
			lightavr;

	private ProgressDialog progressDialog = null;
	
	RelativeLayout layout;


	int tmpVolume;
	boolean state= false; // false : 수면중 아님 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.sensorvalue);
		//setContentView(R.layout.sensormain);
		layout = (RelativeLayout)findViewById(R.id.sensorlayout);
		layout.setBackgroundResource(R.drawable.silence_back1);	

		sensorSwBtn = (Button) findViewById(R.id.sensorSwBtn);
		sensorSwBtn.setBackgroundResource(R.drawable.silence_back1);
		
		audioReader = new AudioReader();
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		handler = new Handler();
		

		// //
		am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

		List<RunningTaskInfo> info = am.getRunningTasks(1);
		ComponentName topActivity = info.get(0).topActivity;
		String name = topActivity.getPackageName();

		// Toast.makeText(this, name,Toast.LENGTH_LONG).show();

		// //
		lgl = new lgListener();
		lnl = new lnListener();

		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		speed_gps = 0;
		speed_ap = 0;

		// location_Gps = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		// location_Network =
		// lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		// speedview = (TextView)findViewById(R.id.speed);

		fileout = (Button) findViewById(R.id.fileout);
		edit = (EditText) findViewById(R.id.filename);
		
		
		sm = (SensorManager) getSystemService(SENSOR_SERVICE);

		accSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		lightSensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
		grySensor = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
		magSensor = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

		accl = new accListener();
		lightl = new lightListener();
		gryl = new gryListener();
		magl = new magListener();

		ax = (TextView) findViewById(R.id.acc_x);
		ax.setVisibility(View.INVISIBLE);
		ay = (TextView) findViewById(R.id.acc_y);
		ay.setVisibility(View.INVISIBLE);
		az = (TextView) findViewById(R.id.acc_z);
		az.setVisibility(View.INVISIBLE);

		light = (TextView) findViewById(R.id.light);
		light.setVisibility(View.INVISIBLE);

		gx = (TextView) findViewById(R.id.Gry_x);
		gy = (TextView) findViewById(R.id.Gry_y);
		gz = (TextView) findViewById(R.id.Gry_z);
		gx.setVisibility(View.INVISIBLE);
		gy.setVisibility(View.INVISIBLE);
		gz.setVisibility(View.INVISIBLE);
		

		mx = (TextView) findViewById(R.id.Mag_x);
		my = (TextView) findViewById(R.id.Mag_y);
		mz = (TextView) findViewById(R.id.Mag_z);
		mx.setVisibility(View.INVISIBLE);
		my.setVisibility(View.INVISIBLE);
		mz.setVisibility(View.INVISIBLE);
		
		

		db = (TextView) findViewById(R.id.dbvalue);
		db.setVisibility(View.INVISIBLE);

		//time = (EditText) findViewById(R.id.time);

		la_gps = (TextView) findViewById(R.id.La_gps);
		lo_gps = (TextView) findViewById(R.id.Lo_gps);
		la_ap = (TextView) findViewById(R.id.La_ap);
		lo_ap = (TextView) findViewById(R.id.Lo_ap);
		s_gps = (TextView) findViewById(R.id.Speed_gps);
		s_ap = (TextView) findViewById(R.id.Speed_ap);
		la_gps.setVisibility(View.INVISIBLE);
		lo_gps.setVisibility(View.INVISIBLE);
		la_ap.setVisibility(View.INVISIBLE);
		lo_ap.setVisibility(View.INVISIBLE);
		s_gps.setVisibility(View.INVISIBLE);
		s_ap.setVisibility(View.INVISIBLE);		
		
		
		
		

		fileout.setOnClickListener(this);
		sensorSwBtn.setOnClickListener(this);
		ap = (AudioManager)getSystemService(AUDIO_SERVICE);
		tmpVolume = ap.getStreamVolume(AudioManager.STREAM_RING);

	}

	public void doStart(View v) {

	}

	boolean isread = true;

	public void onClick(View v) {

		if (v == fileout) {

			if (FILE_OUT) {
				final String textFileName = edit.getText().toString();
				final TextView contentax = ax;
				final TextView contentay = ay;
				final TextView contentaz = az;
				final TextView contentlight = light;
				final TextView contentgx = gx;
				final TextView contentgy = gy;
				final TextView contentgz = gz;
				final TextView contentmx = mx;
				final TextView contentmy = my;
				final TextView contentmz = mz;
				final TextView contentdb = db;

				Log.e("###", "Start audioReader");
				audioReader.startReader(sampleRate, inputBlockSize
						* sampleDecimate,

				new AudioReader.Listener() {
					@Override
					public final void onReadComplete(int dB) {
						//Log.e("###", "receiveDecibel DB : " + dB);
						receiveDecibel(dB);
					}

					@Override
					public void onReadError(int error) {
						//Log.e("###", "receiveDecibel Error DB : " + error);
					}
				});

				showDialog("기록 시작");

				new Thread(new Runnable() {
					public void run() {

						try {
							Thread.sleep(100);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}

						String stracc = "\tax\tay\taz\n";
						String strlight = "\tlight\n";
						String strgry = "\tgx\tgy\tgz\n";
						String strmag = "\tmx\tmy\tmgz\n";
						String strdb = "\tdecibel\n";

						lTime = 100;
						for (int i = 0; i < 100; i++) {
							stracc += i + "\t" + contentax.getText().toString()
									+ "\t" + contentay.getText().toString()
									+ "\t" + contentaz.getText().toString()
									+ "\n";
							strlight += i + "\t"
									+ contentlight.getText().toString() + "\n";
							strgry += i + "\t" + contentgx.getText().toString()
									+ "\t" + contentgy.getText().toString()
									+ "\t" + contentgz.getText().toString()
									+ "\n";
							strmag += i + "\t" + contentmx.getText().toString()
									+ "\t" + contentmy.getText().toString()
									+ "\t" + contentmz.getText().toString()
									+ "\n";
							strdb += i + "\t" + contentdb.getText().toString()
									+ "\n";

							// Log.d("napier", contentdb.getText().toString());
							if (!contentdb.getText().toString().equals("")
									&& !contentdb.getText().toString()
											.equals("db"))
								decibel[i] = Float.parseFloat(contentdb
										.getText().toString());
							if (!contentax.getText().toString().equals("")
									&& !contentax.getText().toString()
											.equals("acc_x"))
								ax_array[i] = Float.parseFloat(contentax
										.getText().toString());
							if (!contentay.getText().toString().equals("")
									&& !contentay.getText().toString()
											.equals("acc_y"))
								ay_array[i] = Float.parseFloat(contentay
										.getText().toString());
							if (!contentaz.getText().toString().equals("")
									&& !contentgz.getText().toString()
											.equals("acc_z"))
								az_array[i] = Float.parseFloat(contentaz
										.getText().toString());

							if (!contentgx.getText().toString().equals("")
									&& !contentgx.getText().toString()
											.equals("gry_x"))
								gx_array[i] = Float.parseFloat(contentgx
										.getText().toString());

							if (!contentgy.getText().toString().equals("")
									&& !contentgy.getText().toString()
											.equals("gry_y"))
								gy_array[i] = Float.parseFloat(contentgy
										.getText().toString());

							if (!contentgz.getText().toString().equals("")
									&& !contentgz.getText().toString()
											.equals("gry_z"))
								gz_array[i] = Float.parseFloat(contentgz
										.getText().toString());

							if (!contentlight.getText().toString().equals("")
									&& !contentlight.getText().toString()
											.equals("light")) {
								Log.d("dy", contentlight.getText().toString());
								light_array[i] = Float.parseFloat(contentlight
										.getText().toString());
							}

							if (i % 2 == 1) {
								lTime--;
							}

							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}

							handler.post(new Runnable() {
								public void run() {
									// setTime();
								}
							});

						}

						BufferedWriter bw = null;
						FileOutputStream fosacc, foslight, fosgry, fosmag, fosdecibel, fosdecibelvar;

						SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
						String curTime = sdf.format(System.currentTimeMillis());

						try {
							fosacc = new FileOutputStream(Environment
									.getExternalStorageDirectory()
									+ "/"
									+ textFileName
									+ "_"
									+ curTime
									+ "_acc"
									+ ".txt");
							fosacc.write(stracc.getBytes());
							fosacc.flush();
							fosacc.close();

							foslight = new FileOutputStream(Environment
									.getExternalStorageDirectory()
									+ "/"
									+ textFileName
									+ "_"
									+ curTime
									+ "_light"
									+ ".txt");
							foslight.write(strlight.getBytes());
							foslight.flush();
							foslight.close();

							fosgry = new FileOutputStream(Environment
									.getExternalStorageDirectory()
									+ "/"
									+ textFileName
									+ "_"
									+ curTime
									+ "_gry"
									+ ".txt");
							fosgry.write(strgry.getBytes());
							fosgry.flush();
							fosgry.close();

							fosmag = new FileOutputStream(Environment
									.getExternalStorageDirectory()
									+ "/"
									+ textFileName
									+ "_"
									+ curTime
									+ "_mag"
									+ ".txt");
							fosmag.write(strmag.getBytes());
							fosmag.flush();
							fosmag.close();

							fosdecibel = new FileOutputStream(Environment
									.getExternalStorageDirectory()
									+ "/"
									+ textFileName
									+ "_"
									+ curTime
									+ "_db"
									+ ".txt");
							fosdecibel.write(strdb.getBytes());
							fosdecibel.flush();
							fosdecibel.close();

							fosdecibelvar = new FileOutputStream(Environment
									.getExternalStorageDirectory()
									+ "/"
									+ textFileName
									+ "_"
									+ curTime
									+ "_dbvar"
									+ ".txt");

							float tf = getVar(decibel);
							Log.d("decibel", "decibel tf / " + decibel);
							String ts = String.format("%f", tf);
							Log.d("decibel", "decibel ts / " + ts);
							// byte tb = Byte.parseByte(ts);

							fosdecibelvar.write(ts.getBytes());
							fosdecibelvar.flush();
							fosdecibelvar.close();

						} catch (FileNotFoundException e) {
							e.printStackTrace();
							Log.e("napier", e.toString());
						} catch (IOException e) {
							e.printStackTrace();
							Log.e("napier", e.toString());
						}

						Log.d("napier", "기록 성공");
						Log.e("###", "Stop audioReader");
						doStop();

						handler.post(new Runnable() {
							public void run() {

								dbvar = getVar(decibel);
								dbavr = getAvg1(decibel);
								axvar = getVar(ax_array);
								ayvar = getVar(ay_array);
								azvar = getVar(az_array);
								gxvar = getVar(gx_array);
								gyvar = getVar(gy_array);
								gzvar = getVar(gz_array);
								lightavr = getAvg1(light_array);

								showDialog(decision(resultspeed, axvar, ayvar,
										azvar, dbavr, dbvar, lightavr));

							}
						});
					}

				}).start();

				// http://netrance.blog.me/110140214261

				isread = false;

			} else {

				final String textFileName = edit.getText().toString();
				final TextView contentax = ax;
				final TextView contentay = ay;
				final TextView contentaz = az;
				final TextView contentlight = light;
				final TextView contentgx = gx;
				final TextView contentgy = gy;
				final TextView contentgz = gz;
				final TextView contentmx = mx;
				final TextView contentmy = my;
				final TextView contentmz = mz;
				final TextView contentdb = db;

				Log.e("###", "Start audioReader");
				audioReader.startReader(sampleRate, inputBlockSize
						* sampleDecimate,

				new AudioReader.Listener() {
					@Override
					public final void onReadComplete(int dB) {
						//Log.e("###", "receiveDecibel DB : " + dB);
						receiveDecibel(dB);
					}

					@Override
					public void onReadError(int error) {
						//Log.e("###", "receiveDecibel Error DB : " + error);
					}
				});

				showDialog("기록 시작");

				new Thread(new Runnable() {
					public void run() {

						try {
							Thread.sleep(1000);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}

						String stracc = "\tax\tay\taz\n";
						String strlight = "\tlight\n";
						String strgry = "\tgx\tgy\tgz\n";
						String strmag = "\tmx\tmy\tmgz\n";
						String strdb = "\tdecibel\n";

						lTime = 100;
						for (int i = 0; i < 100; i++) {
							stracc += i + "\t" + contentax.getText().toString()
									+ "\t" + contentay.getText().toString()
									+ "\t" + contentaz.getText().toString()
									+ "\n";
							strlight += i + "\t"
									+ contentlight.getText().toString() + "\n";
							strgry += i + "\t" + contentgx.getText().toString()
									+ "\t" + contentgy.getText().toString()
									+ "\t" + contentgz.getText().toString()
									+ "\n";
							strmag += i + "\t" + contentmx.getText().toString()
									+ "\t" + contentmy.getText().toString()
									+ "\t" + contentmz.getText().toString()
									+ "\n";
							strdb += i + "\t" + contentdb.getText().toString()
									+ "\n";

							// Log.d("napier", contentdb.getText().toString());
							if (!contentdb.getText().toString().equals("")
									&& !contentdb.getText().toString()
											.equals("db"))
								decibel[i] = Float.parseFloat(contentdb
										.getText().toString());
							if (!contentax.getText().toString().equals("")
									&& !contentax.getText().toString()
											.equals("acc_x"))
								ax_array[i] = Float.parseFloat(contentax
										.getText().toString());
							if (!contentay.getText().toString().equals("")
									&& !contentay.getText().toString()
											.equals("acc_y"))
								ay_array[i] = Float.parseFloat(contentay
										.getText().toString());
							if (!contentaz.getText().toString().equals("")
									&& !contentgz.getText().toString()
											.equals("acc_z"))
								az_array[i] = Float.parseFloat(contentaz
										.getText().toString());

							if (!contentgx.getText().toString().equals("")
									&& !contentgx.getText().toString()
											.equals("gry_x"))
								gx_array[i] = Float.parseFloat(contentgx
										.getText().toString());

							if (!contentgy.getText().toString().equals("")
									&& !contentgy.getText().toString()
											.equals("gry_y"))
								gy_array[i] = Float.parseFloat(contentgy
										.getText().toString());

							if (!contentgz.getText().toString().equals("")
									&& !contentgz.getText().toString()
											.equals("gry_z"))
								gz_array[i] = Float.parseFloat(contentgz
										.getText().toString());

							if (!contentlight.getText().toString().equals("")
									&& !contentlight.getText().toString()
											.equals("light")) {
								Log.d("dy", contentlight.getText().toString());
								light_array[i] = Float.parseFloat(contentlight
										.getText().toString());
							}

							if (i % 2 == 1) {
								lTime--;
							}

							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}

							handler.post(new Runnable() {
								public void run() {
									// setTime();
								}
							});

						}

						Log.e("###", "Stop audioReader");
						doStop();

						handler.post(new Runnable() {
							public void run() {

								dbvar = getVar(decibel);
								dbavr = getAvg1(decibel);
								axvar = getVar(ax_array);
								ayvar = getVar(ay_array);
								azvar = getVar(az_array);
								gxvar = getVar(gx_array);
								gyvar = getVar(gy_array);
								gzvar = getVar(gz_array);
								lightavr = getAvg1(light_array);

								showDialog(decision(resultspeed, axvar, ayvar,
										azvar, dbavr, dbvar, lightavr));

							}
						});
					}

				}).start();

				// http://netrance.blog.me/110140214261

				isread = false;

			}


		
		}else if( v == sensorSwBtn){	//Sensor Switch Btn
			
			if(GV.sensorRun){
				//sensorSwBtn.setText("Sensor Off");
				//sensorSwBtn.setBackgroundColor(Color.argb(100, 195, 195, 195));
				sensorSwBtn.setBackgroundResource(R.drawable.silence_button2);
				GV.sensorRun = false;
			}else{
				runSensor();
				//sensorSwBtn.setText("Sensor On");
				//sensorSwBtn.setBackgroundColor(Color.argb(100, 255, 242, 0));
				sensorSwBtn.setBackgroundResource(R.drawable.silence_button1);
				GV.sensorRun = true;
			}
			
		}

	}

	protected void onPause() {
		super.onPause();
		if (sm != null) {
			sm.unregisterListener(accl);
			sm.unregisterListener(lightl);
			sm.unregisterListener(gryl);
			sm.unregisterListener(magl);
		}
		if (lm != null) {
			lm.removeUpdates(lnl);
		}
	}

	protected void onResume() {
		super.onResume();
		sm.registerListener(accl, accSensor, SensorManager.SENSOR_DELAY_GAME);
		sm.registerListener(lightl, lightSensor,
				SensorManager.SENSOR_DELAY_GAME);
		sm.registerListener(gryl, grySensor, SensorManager.SENSOR_DELAY_GAME);
		sm.registerListener(magl, magSensor, SensorManager.SENSOR_DELAY_GAME);

		lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
				lnl);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, lgl);
		
		
		if(GV.sensorRun){
			//sensorSwBtn.setText("Sensor On");
			//sensorSwBtn.setBackgroundColor(Color.argb(100, 255, 242, 0));
			sensorSwBtn.setBackgroundResource(R.drawable.silence_button1);
		}else{
			//sensorSwBtn.setText("Sensor Off");
			//sensorSwBtn.setBackgroundColor(Color.argb(100, 195, 195, 195));
			sensorSwBtn.setBackgroundResource(R.drawable.silence_button2);
		}

	}

	protected void onDetroy() {

		super.onDestroy();
		if (sm != null) {
			sm.unregisterListener(accl);
			sm.unregisterListener(lightl);
			sm.unregisterListener(gryl);
			sm.unregisterListener(magl);

		}

		if (lm != null) {
			lm.removeUpdates(lnl);
		}

	}

	protected void onStop() {

		super.onStart();
		if (sm != null) {
			sm.unregisterListener(accl);
			sm.unregisterListener(lightl);
			sm.unregisterListener(gryl);
			sm.unregisterListener(magl);

		}

		if (lm != null) {
			lm.removeUpdates(lnl);
		}

	}

	public void doStop() {
		audioReader.stopReader();
	}

	private class accListener implements SensorEventListener {

		public void onAccuracyChanged(Sensor sensor, int sccuracy) {

		}

		public void onSensorChanged(SensorEvent event) {
			if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

				ax.setText(Float.toString(event.values[SensorManager.DATA_X]));
				ay.setText(Float.toString(event.values[SensorManager.DATA_Y]));
				az.setText(Float.toString(event.values[SensorManager.DATA_Z]));

			}
		}

	}

	private class lightListener implements SensorEventListener {

		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}

		public void onSensorChanged(SensorEvent event) {
			if (event.sensor.getType() == Sensor.TYPE_LIGHT) {

				light.setText(Float.toString(event.values[0]));

			}
		}

	}

	private class gryListener implements SensorEventListener {

		public void onAccuracyChanged(Sensor arg0, int arg1) {

		}

		public void onSensorChanged(SensorEvent event) {

			if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE)
				;

			gx.setText(String.format("%.3f", event.values[0]));
			gy.setText(String.format("%.3f", event.values[1]));
			gz.setText(String.format("%.3f", event.values[2]));
		}

	}

	private class magListener implements SensorEventListener {

		public void onAccuracyChanged(Sensor arg0, int arg1) {

		}

		public void onSensorChanged(SensorEvent event) {

			if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
				;

			mx.setText(String.format("%.3f", event.values[0]));
			my.setText(String.format("%.3f", event.values[1]));
			mz.setText(String.format("%.3f", event.values[2]));

		}

	}

	private class lnListener implements LocationListener {

		public void onLocationChanged(Location location) {

			Log.d("dy_location", "Network / " + location.toString());
			speed_ap = speedCheck(location);
			la_ap.setText("" + location.getLatitude());
			lo_ap.setText("" + location.getLongitude());

			if (speed_ap == 0)
				s_ap.setText("0");
			else
				s_ap.setText("" + speed_ap);

			// speedview.setText(resultspeed+" ");

		}

		public void onProviderDisabled(String provider) {

		}

		public void onProviderEnabled(String provider) {

		}

		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

	}

	private class lgListener implements LocationListener {

		public void onLocationChanged(Location location) {

			Log.d("dy_location", "GPS / " + location.toString());
			speed_gps = speedCheck(location);
			la_gps.setText("" + location.getLatitude());
			lo_gps.setText("" + location.getLongitude());

			if (speed_gps == 0)
				s_gps.setText("0");
			else
				s_gps.setText("" + speed_gps);

			// speedview.setText(resultspeed+" ");

		}

		public void onProviderDisabled(String provider) {

		}

		public void onProviderEnabled(String provider) {

		}

		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

	}

	int mDBvalue;

	private void receiveDecibel(final int dBvalue) {
		mDBvalue = dBvalue;
		Log.e("###", dBvalue + " dB");

		// db.setText("##"+dBvalue);
		handler.post(new Runnable() {
			public void run() {
				setDecibel();
			}
		});
	}

	public void setDecibel() {
		db.setText(mDBvalue + "");
	}

	int lTime = 0;

	// public void setTime() {
	// time.setText(lTime + "");
	// }

	public void showDialog(String str) {
		
		
		
		
		
		
		
		
		try {
			Builder dlg = new AlertDialog.Builder(this);
			dlg.setTitle("알림")
					.setMessage(str)
					.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int speedCheck(Location location) {

		int speed;

		if (location != null) {

			preTime = curTime;
			prelng = lng;
			prelat = lat;

			lat = location.getLatitude();
			lng = location.getLongitude();

			curTime = location.getTime();
			deltaTime = (curTime - preTime);

			Location.distanceBetween(prelat, prelng, lat, lng, distance);

			speed = (int) (((distance[0] / deltaTime) * 36) / 10);

		} else {
			speed = 0;

		}

		return speed;

	}

	public float getAvg1(float[] array) { // 평균구하는 메소드

		float nTotal = 0;
		float nAvg = 0;

		for (int i = 0; i < array.length; i++) {
			nTotal += array[i];
		}
		nAvg = nTotal / array.length;

		return nAvg;
	}

	public float getVar(float[] array) { // 분산구하는 메소드
		float nTemp = 0;
		float nVar = 0;

		for (int i = 0; i < array.length; i++) {
			Log.d("getVar", "array" + array[i]);
			nTemp += (array[i] - getAvg1(array)) * (array[i] - getAvg1(array));
		}
		Log.d("getVar", "nTemp" + nTemp + " / nVar" + nVar);
		nVar = nTemp / (array.length - 1);

		return nVar;
	}

	public String decision(float Speed, float axvar, float ayvar, float azvar,
			float dbavr, float dbvar, float lightavr) {

		Log.i("dy", "db평균 : " + dbavr + " db분산 " + dbvar + "조도평균  : "
				+ lightavr+"/"+Speed+"/"+axvar+"/"+ayvar+"/"+azvar);

		if (speed_gps > 10)
			// return "교통수단 이용 중";
			return "수면중이 아닙니다";

		// 요건 network로 위치 구하기
		// if (speed_ap > 10)
		// return "Using transprtation";

		else {

			if (axvar > 1 || ayvar > 1)// || azvar > 1) 
			{

				// return "움직임";
				return "수면중이 아닙니다";
			}

			else {
				/*if (dbvar > 150) {

					// return "회의 중";
					return "수면중이 아닙니다";
				}

				else {*/

					if (dbavr < 1)// && dbvar < 100) 
					{

						if (lightavr < 4)
							return "수면 중";

						else
							// return "공부 중";
							return "수면중이 아닙니다";

					//}

				}

			}
		}
		return "Cannat Know";

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	private void runSensor(){
		
		final String textFileName = edit.getText().toString();
		final TextView contentax = ax;
		final TextView contentay = ay;
		final TextView contentaz = az;
		final TextView contentlight = light;
		final TextView contentgx = gx;
		final TextView contentgy = gy;
		final TextView contentgz = gz;
		final TextView contentmx = mx;
		final TextView contentmy = my;
		final TextView contentmz = mz;
		final TextView contentdb = db;

		Log.e("###", "Start audioReader");
		audioReader.startReader(sampleRate, inputBlockSize
				* sampleDecimate,

		new AudioReader.Listener() {
			@Override
			public final void onReadComplete(int dB) {
				//Log.e("###", "receiveDecibel DB : " + dB);
				receiveDecibel(dB);
			}

			@Override
			public void onReadError(int error) {
				//Log.e("###", "receiveDecibel Error DB : " + error);
			}
		});

		new Thread(new Runnable() {
			public void run() {

				while (GV.sensorRun) {

					
					for (int i = 0; i < SENSOR_TERM; i++) {

						if (!GV.sensorRun) {
							Log.e("###", "Stop audioReader");
							doStop();
							break;
						}

						if (!contentdb.getText().toString().equals("")
								&& !contentdb.getText().toString().equals("db"))
							decibel[i] = Float.parseFloat(contentdb.getText()
									.toString());
						if (!contentax.getText().toString().equals("")
								&& !contentax.getText().toString()
										.equals("acc_x"))
							ax_array[i] = Float.parseFloat(contentax.getText()
									.toString());
						if (!contentay.getText().toString().equals("")
								&& !contentay.getText().toString()
										.equals("acc_y"))
							ay_array[i] = Float.parseFloat(contentay.getText()
									.toString());
						if (!contentaz.getText().toString().equals("")
								&& !contentgz.getText().toString()
										.equals("acc_z"))
							az_array[i] = Float.parseFloat(contentaz.getText()
									.toString());

						if (!contentgx.getText().toString().equals("")
								&& !contentgx.getText().toString()
										.equals("gry_x"))
							gx_array[i] = Float.parseFloat(contentgx.getText()
									.toString());

						if (!contentgy.getText().toString().equals("")
								&& !contentgy.getText().toString()
										.equals("gry_y"))
							gy_array[i] = Float.parseFloat(contentgy.getText()
									.toString());

						if (!contentgz.getText().toString().equals("")
								&& !contentgz.getText().toString()
										.equals("gry_z"))
							gz_array[i] = Float.parseFloat(contentgz.getText()
									.toString());

						if (!contentlight.getText().toString().equals("")
								&& !contentlight.getText().toString()
										.equals("light")) {
							Log.d("dy", contentlight.getText().toString());
							light_array[i] = Float.parseFloat(contentlight
									.getText().toString());
						}


						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

					}

					handler.post(new Runnable() {
						public void run() {
							
							if(!GV.sensorRun) return;

							dbvar = getVar(decibel);
							dbavr = getAvg1(decibel);
							axvar = getVar(ax_array);
							ayvar = getVar(ay_array);
							azvar = getVar(az_array);
							gxvar = getVar(gx_array);
							gyvar = getVar(gy_array);
							gzvar = getVar(gz_array);
							lightavr = getAvg1(light_array);
							
							String str ;
							str =decision(resultspeed, axvar, ayvar,azvar, dbavr, dbvar, lightavr);

							
							//showDialog(str);	
				

							if(str.equals("수면 중"))
							{
								if(state==false)
								{
									showDialog(str);								
									ap.setStreamVolume(AudioManager.STREAM_RING, 0, AudioManager.MODE_NORMAL);	
								}	
								state = true;
							
								
								/*
							
								NotificationManager notificationManager = (NotificationManager) 
										getSystemService(NOTIFICATION_SERVICE);
							Notification notification = new Notification(R.drawable.ic_launcher,
									"알려드립니다", System.currentTimeMillis());
							// 이용자가 통지를 확인한 후에는 통지를 표시하지 않도록 설정
							notification.flags |= Notification.FLAG_AUTO_CANCEL;

							Intent intent = new Intent();
							PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
							notification.setLatestEventInfo(this, "우편물 도착","소포가 배달되어 관리실에 있습니다", activity);
							notification.number += 1;
							notificationManager.notify(0, notification);*/
								

							//GV.nm = (NotificationManager) GV.context.getSystemService(NOTIFICATION_SERVICE);
							
								/*NotificationManager nm = (NotificationManager) GV.context.getSystemService(NOTIFICATION_SERVICE);
							
								Notification notif = new NotificationCompat.Builder(getApplicationContext())
													.setContentTitle("내 상태")
													.setContentText(decision(resultspeed, axvar, ayvar,
															azvar, dbavr, dbvar, lightavr))
													.setTicker("SmartphoneContext")
													.setAutoCancel(true)
													.setContentIntent(null)
													.build();
													
									
							//notif.vibrate = GV.vibrate;							
							nm.notify(7777, notif); */			
																						
														
							
							}							
							else 
							{
								if(state==true)
								{
									showDialog(str);
									ap.setStreamVolume(AudioManager.STREAM_RING, tmpVolume, AudioManager.MODE_NORMAL);
								}
								state = false;								
							}
						}
					});
				}

			}

		}).start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		
	}
	

}
